<template>
  <div
    ref="scrollList"
    class="scroll-list text-sm p-1"
    :style="{ height: containerHeight + 'px' }"
  >
    <ul>
      <li
        v-for="(item, index) in items"
        :key="index"
        :style="{
          backgroundColor:
            index % 2 === 0 ? 'rgba(64, 195, 200, 0.3)' : 'rgba(0, 0, 0, 0.3)'
        }"
      >
        <span class="ml-20">{{ item }}</span>
      </li>
    </ul>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, defineProps } from "vue";

const items = ref<string[]>([]);
const containerHeight = 200;
const scrollSpeed = 100;
let timer: NodeJS.Timeout | null = null;

const props = defineProps({
  data: Array
});
const data = props.data;

const fetchItems = () => {
  setTimeout(() => {
    items.value = data;
  }, 1000);
};

// 启动自动滚动
const startAutoScroll = () => {
  timer = setInterval(() => {
    const scrollList = document.querySelector(".scroll-list");
    if (scrollList) {
      scrollList.scrollTop += 1; // 每次滚动一个像素，可根据需要调整
      if (scrollList.scrollTop >= scrollList.scrollHeight - containerHeight) {
        // 当滚动到底部时回到顶部
        scrollList.scrollTop = 0;
      }
    }
  }, scrollSpeed);
};

onMounted(() => {
  // 初始化数据
  fetchItems();
  // 启动自动滚动
  startAutoScroll();
});

onBeforeUnmount(() => {
  // 组件销毁时清除定时器
  if (timer) clearInterval(timer);
});
</script>

<style scoped lang="scss">
.scroll-list {
  overflow-y: auto;
  //border: 1px solid #ccc;
}

.scroll-list ul {
  padding: 0;
  margin: 0;
  list-style-type: none;
}

.scroll-list li {
  padding: 5px;
  border-bottom: 1px solid #ffffff;
}
</style>
